package com.jdaw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdaw.reggie.common.BaseContext;
import com.jdaw.reggie.common.R;
import com.jdaw.reggie.entity.Employee;
import com.jdaw.reggie.entity.Orders;
import com.jdaw.reggie.entity.User;
import com.jdaw.reggie.service.OrderService;
import com.jdaw.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;

    /**
     * 用户下单
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("用户下单成功");
    }

    /**
     * 后端展示订单
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime){
        log.info(beginTime+endTime);
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(number), Orders::getNumber, number);
        if(beginTime!=null&&endTime!=null) {
            queryWrapper.between(Orders::getOrderTime, beginTime, endTime);
        }
        queryWrapper.orderByDesc(Orders::getAmount);
        orderService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 更改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> order(@RequestBody Orders orders){
        log.info(orders.toString());
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,orders.getId());
        Orders one = orderService.getOne(queryWrapper);
        Integer status = one.getStatus();
        one.setStatus(status+1);
        orderService.updateById(one);
        return R.success("订单信息已更改");
    }

    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize){
        Page page1=new Page(page,pageSize);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(User::getId, BaseContext.getCurrentId());
        userService.page(page1,queryWrapper);
        return R.success(page1);
    }


}
